package com.mdd.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.mdd.admin.esign.FileAnd;
import com.mdd.admin.esign.SignService;
import com.mdd.admin.esign.Template;
import com.mdd.admin.esign.comm.EsignHttpResponse;
import com.mdd.admin.esign.exception.EsignDemoException;
import com.mdd.admin.service.FileService;
import com.mdd.admin.validate.GetInformationDTO;
import com.mdd.common.core.AjaxResult;
import com.mdd.common.entity.CreateTemplate;
import com.mdd.common.entity.LegalCaseContract;
import com.mdd.common.entity.user.User;
import com.mdd.common.mapper.CreateTemplateMapper;
import com.mdd.common.mapper.LegalCaseContractMapper;
import com.mdd.common.mapper.user.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private CreateTemplateMapper createTemplateMapper; //制作模板链接表

    @Autowired
    private LegalCaseContractMapper legalCaseContractMapper;//案件合同记录表

    @Autowired
    private UserMapper userMapper; //用户表

    @Override
    public Map<String, Object> uploadFile(MultipartFile file) {
        Assert.notNull(file, "合同上传失败");
        try {
            // 将MultipartFile转化为本地File
            File localFile = new File("D:\\" + file.getOriginalFilename());
            file.transferTo(localFile);
            String rootFolder = localFile.getAbsolutePath();
            // 获取文件上传地址和文件ID
            EsignHttpResponse getUploadUrlResponse = FileAnd.getUploadUrl(rootFolder);
            JsonObject getUploadUrlJsonObject = new Gson().fromJson(getUploadUrlResponse.getBody(), JsonObject.class);
            JsonObject data = getUploadUrlJsonObject.getAsJsonObject("data");
            String fileId = data.get("fileId").getAsString();
            String fileUploadUrl = data.get("fileUploadUrl").getAsString();
            // 文件流上传到指定的上传地址
            EsignHttpResponse uploadFileResponse = FileAnd.uploadFile(fileUploadUrl, rootFolder);
            JsonObject uploadFileResponseJsonObject = new Gson().fromJson(uploadFileResponse.getBody(), JsonObject.class);
            String code = uploadFileResponseJsonObject.get("errCode").getAsString();
            System.out.println("文件上传成功，状态码:" + code);
            String fileDownloadUrl = "";
            // 轮询查询文件上传状态
            int i = 0;
            while (i < 3) {
                EsignHttpResponse fileStatus = FileAnd.getFileStatus(fileId); //根据文件id获取文件状态
                JsonObject fileStatusJsonObject = new Gson().fromJson(fileStatus.getBody(), JsonObject.class);
                String status = fileStatusJsonObject.getAsJsonObject("data").get("fileStatus").getAsString();
                fileDownloadUrl = fileStatusJsonObject.getAsJsonObject("data").get("fileDownloadUrl").getAsString();
                System.out.println(String.format("查询文件状态执行第%s次", i + 1));
                if ("2".equalsIgnoreCase(status) || "5".equalsIgnoreCase(status)) { //如果状态等于2 或者 5
                    System.out.println("文件准备完成");
                }
                System.out.println("文件未准备完成,等待两秒重新查询");
                TimeUnit.SECONDS.sleep(2);
                i++;
            }
            //调用获取制作合同模板链接
            String docTemplateId = getTemplateCreateUrl(file.getOriginalFilename(), fileId);
//                //创建map返回文件id以及文件上传地址
            Map<String, Object> map = new HashMap<>();
            map.put("fileId", fileId);
            map.put("fileDownloadUrl", fileDownloadUrl);
            map.put("docTemplateId", docTemplateId);
            return map;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public AjaxResult<Map<String, String>> viewSigningDetails(GetInformationDTO dto) throws EsignDemoException {
        Map<String, String> map = new HashMap<>();
        Gson gson = new Gson();
        LegalCaseContract legalCaseContract = legalCaseContractMapper.selectById(dto.getId());
        Assert.notNull(legalCaseContract, "没有当前案件合同记录");
        //查询用户
        User user = userMapper.selectOne(
                new QueryWrapper<User>()
                        .eq("id", legalCaseContract.getUserId())
                        .eq("is_delete", 0)
                        .eq("is_disable", 0)
        );
        Assert.notNull(user, "当前流程关联用户为空");
        String shortUrl = "";
        String url = "";
        //获取页面预览链接
        try {
            EsignHttpResponse signUrl = SignService.signUrlTwo(user, legalCaseContract);
            JsonObject signUrlJsonObject = gson.fromJson(signUrl.getBody(), JsonObject.class);
            String code = signUrlJsonObject.get("code").getAsString();
            if (code.equals("0")) {
                JsonObject signUrlData = signUrlJsonObject.getAsJsonObject("data");
                shortUrl = signUrlData.get("shortUrl").getAsString();
                url = signUrlData.get("url").getAsString();
                map.put("shortUrl", shortUrl);
                map.put("url", url);
                //保存预览链接给用户
                user.setSignPreviewLink(shortUrl);
                userMapper.updateById(user);
                return AjaxResult.success("获取预览链接成功",map);
            } else {
                String message = signUrlJsonObject.get("message").getAsString();
                map.put("message", message);
            }
            return AjaxResult.failed(1,"获取预览链接失败",map);
        } catch (EsignDemoException e) {
            e.printStackTrace();
            throw new EsignDemoException("获取预览链接发生错误", e);
        }
    }

    /**
     * 获取制作合同模板页面链接
     *
     * @param docTemplateName
     * @param fileId
     * @return
     */
    private String getTemplateCreateUrl(String docTemplateName, String fileId) {
        //这里得保存一下当前的制作模板id以及链接
        CreateTemplate createTemplate = new CreateTemplate();
        try {
            EsignHttpResponse esignHttpResponse = Template.getTemplateCreateUrl(docTemplateName, fileId);
            JsonObject getTemplateCreateUrlJsonObject = new Gson().fromJson(esignHttpResponse.getBody(), JsonObject.class);
            String templateCreateUrl = getTemplateCreateUrlJsonObject.getAsJsonObject("data").get("docTemplateCreateUrl").getAsString();
            String docTemplateId = getTemplateCreateUrlJsonObject.getAsJsonObject("data").get("docTemplateId").getAsString();

            createTemplate.setDocTemplateId(docTemplateId);//模板id
            createTemplate.setFileId(fileId);//文件id
            createTemplate.setDocTemplateCreateLongUrl(templateCreateUrl);//制作链接
            createTemplateMapper.insert(createTemplate);
            return docTemplateId;
        } catch (EsignDemoException e) {
            e.printStackTrace();
        }
        return "";
    }
}
